<?php

namespace Biz\tools;

use Doraemon\tools\Log;

/**
 * 万邦
 * https://open.onebound.cn/
 */
class OneBound
{
    const TAOBAO_ITEM_GET = 'https://api-gw.onebound.cn/taobao/item_get';
    //const TAOBAO_ITEM_GET = 'https://api-1.onebound.cn/taobao/item_get';//1，2，3，4

    const TAOBAO_ITEM_GET_DESC = 'https://api-gw.onebound.cn/taobao/item_get_desc';

    const API_KEY = 't8611186421';
    const SECRET = '53d4521082098953913033b90432d687';

    public static function getTaoBaoItemInfo($itemId, $type = RealUrl::URL_TYPE_TAOBAO)
    {
        $result = [];
        if (!in_array($type, [RealUrl::URL_TYPE_TAOBAO, RealUrl::URL_TYPE_TMALL])) {
            return $result;
        }
        $url = self::TAOBAO_ITEM_GET . '?key=' . self::API_KEY . '&secret=' . self::SECRET . '&num_iid=' . $itemId . '&is_promotion=1&cache=no';
        $data = self::_getApi($url);
        if ($data && isset($data['item']) && $data['item'] && isset($data['item']['num_iid']) && $data['item']['num_iid']) {
            Log::info('获取淘宝商品成功#item_id:' . $itemId . '#url:' . $url, $data);
            $itemInfo = $data['item'];
            $sellerInfo = $itemInfo['seller_info'] ?? [];
            $itemImgs = $itemInfo['item_imgs'] ?? [];
            $descImages = $itemInfo['desc_img'] ?? [];
            $desc = $itemInfo['desc'] ?? '';
            $coverImg = $itemInfo['pic_url'] ?? '';
            $price = $itemInfo['price'];
            $skus = $itemInfo['skus'];
            $props = $itemInfo['props'];
            if ($coverImg) {
                $parseUrlArr = parse_url($coverImg);
                $coverImg = 'https://' . $parseUrlArr['host'] . $parseUrlArr['path'];
            }
            $imgs = [];
            foreach ($itemImgs as $imgRow) {
                $parseUrlArr = parse_url($imgRow['url']);
                if ($parseUrlArr) {
                    $imgUrl = 'https://' . $parseUrlArr['host'] . $parseUrlArr['path'];
                    if (!$coverImg) {
                        $coverImg = $imgUrl;
                    }
                    $imgs[] = $imgUrl;
                }
            }
            if (empty($descImages)) {
                if (!empty($desc)) {
                    $descImages = self::getImgUrl($desc);
                } else {
                    $descImages = self::getTaoBaoItemDesc($itemId);
                }
            }
            $content = '';
            foreach ($descImages as $descImgsRow) {
                $parseUrlArr = parse_url($descImgsRow);
                $detailImgUrl = 'https://' . $parseUrlArr['host'] . $parseUrlArr['path'];
                $content .= '<img src="' . $detailImgUrl . '">';
            }
            $priceArr = [];
            if (isset($skus['sku']) && $skus['sku']) {
                foreach ($skus['sku'] as $row) {
                    $priceArr[] = $row['price'];
                }
            }
            $maxPrice = $priceArr ? max($priceArr) : $price;
            $minPrice = $priceArr ? min($priceArr) : $price;

            $brandName = '';
            $material = [];//材质
            $style = [];//风格
            if ($props) {
                foreach ($props as $row) {
                    if ($row['name'] == '品牌') {
                        $brandName = $row['value'] ?? '';
                    } else if ($row['name'] == '风格') {
                        $style[] = $row['value'];
                    } else if ($row['name'] == '材质') {
                        $material[] = $row['value'];
                    } else if (strpos($row['name'], '材质') !== false && $row['value'] && $row['value'] != '无') {
                        $material[] = $row['value'];
                    }
                }
            }
            $tags = [];
            if (!empty($style)) {
                $tags['style'] = array_values(array_unique($style));
            }
            if (!empty($material)) {
                $tags['material'] = array_values(array_unique($material));
            }
            $shopId = $itemInfo['shop_id'] ?? 0;
            $sellerId = $itemInfo['seller_id'] ?? 0;
            if (empty($shopId)) {
                $shopId = ($sellerInfo && isset($sellerInfo['sid']) && $sellerInfo['sid']) ? $sellerInfo['sid'] : ($sellerInfo['shop_id'] ?? 0);
            }
            if (empty($sellerId)) {
                $sellerId = ($sellerInfo && isset($sellerInfo['user_num_id']) && $sellerInfo['user_num_id']) ? $sellerInfo['user_num_id'] : ($sellerInfo['seller_id'] ?? 0);
            }
            $result = [
                'title' => $itemInfo['title'],
                'channel_type' => $type,
                'channel_spu_id' => $itemId,
                'channel_shop_id' => $shopId,
                'channel_seller_id' => $sellerId,
                'channel_shop_name' => $sellerInfo ? $sellerInfo['shop_name'] : $itemInfo['nick'],
                'channel_category_name' => '',
                'channel_category_id' => 0,
                'channel_brand' => $itemInfo['brand'] ?? $brandName,
                'min_price' => $minPrice,
                'max_price' => $maxPrice,
                'cover_img' => $coverImg,
                'tags' => !empty($tags) ? json_encode($tags, JSON_UNESCAPED_UNICODE) : '',
                'imgs' => $imgs ? json_encode($imgs, JSON_UNESCAPED_UNICODE) : '',
                'content' => $content,
            ];
        } else {
            Log::debug('获取淘宝商品失败#item_id:' . $itemId . '#url:' . $url, $data);
        }
        return $result;
    }

    public static function getTaoBaoItemDesc($itemId)
    {
        $descImgs = [];
        $url = self::TAOBAO_ITEM_GET_DESC . '?key=' . self::API_KEY . '&secret=' . self::SECRET . '&num_iid=' . $itemId . '&is_promotion=1&cache=no';
        $data = self::_getApi($url);
        if ($data && isset($data['item']) && $data['item']) {
            Log::info('查询淘宝商品详情成功#item_id:' . $itemId . '#url:' . $url, $data);
            $descStr = $data['item']['desc'];
            $descImgs = self::getImgUrl($descStr);
        } else {
            Log::debug('查询淘宝商品详情失败#item_id:' . $itemId . '#url:' . $url, $data);
        }
        return $descImgs;
    }

    private static function getImgUrl($str)
    {
        $imgs = [];
        $preg = '/<img.*?src=[\"|\']?(.*?)[\"|\']?\s.*?>/i';
        preg_match_all($preg, $str, $imgArr);
        if ($imgArr && isset($imgArr[1])) {
            $imgs = $imgArr[1];
        }
        return $imgs;
    }

    private static function _getApi($url)
    {
        $method = 'GET';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        curl_setopt($curl, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($curl, CURLOPT_ENCODING, "gzip");
        curl_setopt($curl, CURLOPT_TIMEOUT, 20);
        $data = curl_exec($curl);
        curl_close($curl);
        $data = json_decode($data, true);
        if (!empty($data)) {
            return $data;
        } else {
            Log::debug('curl查询失败#url:' . $url, $data);
            return [];
        }
    }
}